package com.lawrence.demo;

import com.lawrence.util.DruidUtil;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * JDBC 批量处理数据
 */

public class JdbcDemo02 {

    public static String getName(){
        int r = (int)Math.random() * 100;
        String name = r + "";
        return name;
    }

    public static String getSex(){
        String sex;
        int r = (int)Math.random() * 100;
        if (r % 2 != 0) {
            sex = "男";
        } else {
            sex = "女";
        }
        return sex;
    }

    //批量插入操作
    public void insert() throws Exception {
        DataSource dataSource = DruidUtil.getDataSource();
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        String sql = "insert into Student(s_id,s_name,s_birth,s_sex) values(?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        for (int i = 11; i < 100; i++) {
            ps.setInt(1, i);
            ps.setString(2,getName());
            ps.setString(3,"2021.12.17");
            ps.setString(4,getSex());
            //将要执行的SQL语句先添加进去，不执行
            ps.addBatch();
        }
        //执行
        int[] ints = ps.executeBatch();
        connection.commit();
        System.out.println(ints);
    }
}
